<template>
  <view class="multi-image-uploader">
    <view class="upload-header">
      <text class="upload-title">{{ title }}</text>
      <text class="upload-count">{{ images.length }}/{{ maxCount }}</text>
    </view>
    
    <view class="upload-tip" v-if="tip">
      <text class="tip-icon">💡</text>
      <text class="tip-text">{{ tip }}</text>
    </view>
    
    <view class="upload-grid">
      <!-- 已上传的图片 -->
      <view 
        v-for="(image, index) in images" 
        :key="index"
        class="upload-item"
      >
        <view class="upload-box uploaded" @click="previewImage(image, index)">
          <image 
            :src="image" 
            class="uploaded-image"
            mode="aspectFill"
          />
          <view class="delete-btn" @click.stop="deleteImage(index)">
            <text class="delete-icon">×</text>
          </view>
        </view>
      </view>
      
      <!-- 添加按钮 -->
      <view 
        v-if="images.length < maxCount"
        class="upload-item"
      >
        <view class="upload-box add-btn" @click="chooseImage">
          <text class="add-icon">+</text>
          <text class="add-text">添加图片</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  name: 'MultiImageUploader',
  props: {
    // 图片数组
    images: {
      type: Array,
      default: () => []
    },
    // 标题
    title: {
      type: String,
      default: '上传图片'
    },
    // 提示文本
    tip: {
      type: String,
      default: ''
    },
    // 最大数量
    maxCount: {
      type: Number,
      default: 9
    },
    // 上传接口URL
    uploadUrl: {
      type: String,
      default: 'https://xindian66.xyz/api/file/upload'
    },
    // 文件模块分类（如：order/takeOut/send）
    module: {
      type: String,
      default: 'default'
    }
  },
  methods: {
    // 选择图片
    chooseImage() {
      const remainCount = this.maxCount - this.images.length
      if (remainCount <= 0) {
        uni.showToast({ title: `最多只能上传${this.maxCount}张图片`, icon: 'none' })
        return
      }
      
      uni.chooseImage({
        count: Math.min(remainCount, 9), // 一次最多选择9张
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          // 批量上传
          this.uploadImages(res.tempFilePaths)
        },
        fail: (error) => {
          console.error('选择图片失败:', error)
          uni.showToast({ title: '选择图片失败', icon: 'none' })
        }
      })
    },

    // 批量上传图片
    async uploadImages(filePaths) {
      uni.showLoading({ title: `上传中(0/${filePaths.length})...` })
      
      const uploadPromises = filePaths.map((filePath, index) => 
        this.uploadSingleImage(filePath, index, filePaths.length)
      )
      
      try {
        const results = await Promise.all(uploadPromises)
        const successUrls = results.filter(url => url).map(result => result.url)
        
        // 更新图片数组
        const newImages = [...this.images, ...successUrls]
        this.$emit('update:images', newImages)
        
        uni.hideLoading()
        uni.showToast({ 
          title: `成功上传${successUrls.length}张图片`, 
          icon: 'success' 
        })
        
        // 触发上传成功事件
        this.$emit('upload-success', {
          images: newImages,
          newImages: successUrls
        })
        
      } catch (error) {
        uni.hideLoading()
        console.error('批量上传失败:', error)
        uni.showToast({ title: '部分图片上传失败', icon: 'none' })
        
        // 触发上传失败事件
        this.$emit('upload-error', { error })
      }
    },

    // 上传单张图片
    async uploadSingleImage(filePath, index, total) {
      return new Promise((resolve, reject) => {
        uni.uploadFile({
          url: this.uploadUrl,
          filePath: filePath,
          name: 'file',
          formData: {
            module: this.module  // 传递模块参数
          },
          header: {
            'ss_satoken': uni.getStorageSync('ss_satoken') || ''
          },
          success: (res) => {
            try {
              const data = JSON.parse(res.data)
              if (data.code === 0) {
                // 更新进度
                uni.showLoading({ title: `上传中(${index + 1}/${total})...` })
                resolve(data.data)
              } else {
                console.error(`图片${index + 1}上传失败:`, data.msg)
                resolve(null)
              }
            } catch (e) {
              console.error(`图片${index + 1}响应解析失败:`, e)
              resolve(null)
            }
          },
          fail: (error) => {
            console.error(`图片${index + 1}上传失败:`, error)
            resolve(null)
          }
        })
      })
    },

    // 删除图片
    deleteImage(index) {
      uni.showModal({
        title: '确认删除',
        content: '确定要删除这张图片吗？',
        success: (res) => {
          if (res.confirm) {
            const newImages = [...this.images]
            newImages.splice(index, 1)
            this.$emit('update:images', newImages)
            
            uni.showToast({ title: '删除成功', icon: 'success' })
          }
        }
      })
    },

    // 预览图片
    previewImage(currentUrl, currentIndex) {
      uni.previewImage({
        urls: this.images,
        current: currentIndex
      })
    }
  }
}
</script>

<style scoped>
.multi-image-uploader {
  margin-bottom: 24rpx;
}

.upload-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16rpx;
}

.upload-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
}

.upload-count {
  font-size: 24rpx;
  color: #666;
  background: #f5f5f5;
  padding: 4rpx 12rpx;
  border-radius: 12rpx;
}

.upload-tip {
  background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%);
  border-radius: 12rpx;
  padding: 20rpx;
  display: flex;
  align-items: center;
  gap: 12rpx;
  margin-bottom: 20rpx;
}

.tip-icon {
  font-size: 32rpx;
}

.tip-text {
  flex: 1;
  font-size: 24rpx;
  color: #1976d2;
  line-height: 1.4;
}

.upload-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
}

.upload-item {
  width: 200rpx;
  height: 200rpx;
}

.upload-box {
  width: 100%;
  height: 100%;
  border-radius: 12rpx;
  overflow: hidden;
  position: relative;
}

.upload-box.uploaded {
  border: 2rpx solid #e0e0e0;
}

.upload-box.add-btn {
  border: 2rpx dashed #ddd;
  background: #fafafa;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 8rpx;
}

.uploaded-image {
  width: 100%;
  height: 100%;
}

.delete-btn {
  position: absolute;
  top: 8rpx;
  right: 8rpx;
  width: 48rpx;
  height: 48rpx;
  background: rgba(0, 0, 0, 0.6);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.delete-icon {
  color: #fff;
  font-size: 32rpx;
  font-weight: bold;
  line-height: 1;
}

.add-icon {
  font-size: 48rpx;
  color: #999;
  font-weight: 300;
}

.add-text {
  font-size: 24rpx;
  color: #999;
}
</style>
